//
// Created by chench on 2/20/22.
//

#include "sm.h"


void main(){
    char *key = "0123456789abcdef";
    printf("key:%s\r\n", key);
    char *str = "0123456789abcdef0123456789abcdef";
    printf("str:%s\r\n", str);
    char *buf = sms4(1, key, str);
    char *tmp = sms4(0, key, str);
    printf("tmp:%s\r\n", tmp);

}


char *sms4(int den, char *key, char *str) {

    //密钥
    sms4_key_t sms4_key;
    memcpy(sms4_key.rk, key, 16);
    if (den) {
        //加密
        sms4_set_encrypt_key(&sms4_key, key);
    } else {
        //解密
        sms4_set_decrypt_key(&sms4_key, key);
    }

    //十六字节填充
    int str_len = strlen(str);
    int pad_len = str_len % 16;//填充余数
    int tmp_len = str_len + 16 - pad_len;
    char *tmp = malloc(tmp_len);
    memcpy(tmp, str, str_len);
    memset(tmp + str_len, pad_len, pad_len);

    // 存储返回数据
    char *buf = malloc(tmp_len);
    //十六字节循环
    for (int i = 0; i <= str_len / 16; i++) {
        // sms4_encrypt = sms4_decrypt
        sms4_encrypt(tmp + 16 * i, buf + 16 * i, &sms4_key);
    }

    return buf;


}

